package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"vid-man2/handler"
	"vid-man2/pkg"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

// 定义中间
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		fmt.Println("获取到token参数：", tokenString)
		if tokenString == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "token为空",
			})
			c.Abort()
		}
		getToken, err := pkg.GetJwtToken(tokenString)
		if err != "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "token验证失败",
			})
			c.Abort()
		}
		fmt.Println("解析完token参数后：", getToken)
		c.Set("uid", getToken["uid"])
		c.Next()
	}
}
func Init() *gin.Engine {
	r := gin.Default()
	r.Use(Cors())
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	r.GET("/login", handler.Login)

	r.POST("/add", handler.Add)
	r.GET("/detail", handler.Detail)
	//r.GET("/list", MiddleWare(), handler.List)
	r.GET("/list", handler.List)

	r.Static("/static", "./static")
	return r
}
